package C022;

import java.util.Arrays;

/**
 * ClassName: Main2
 * Package: C022
 * Description:
 *
 * @Author BCXJ
 * @Create 2024/12/7 12:18
 * @Version 1.0
 * @Since 1.0
 */
public class Main2 {
    public static void main(String[] args) {
        int num = 1000;
        int size = 20;
        int length = 100;
        for (int i = 0; i < num; i++) {
            int[] arr1 = generateRandomArr(size, length);
            int[] arr2 = Arrays.copyOf(arr1, arr1.length);
            long i1 = reversePairs(arr1);
            long i2 = reversePairs2(arr2);
            if(i1 != i2) {
                System.out.println("error !!!!");
                System.out.println(Arrays.toString(arr1));
                System.out.println(Arrays.toString(arr2));
                System.out.println(i1);
                System.out.println(i2);
                return;
            }
        }
        System.out.println("success !!!!");

//        int[] arr = {13, 17, 5, 7};
//        System.out.println(reversePairs2(arr));
//        System.out.println(reversePairs(arr));

    }

    public static int[] generateRandomArr(int n, int size) {
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = (int) (Math.random() * size);
        }
        return arr;
    }

    public static int reversePairs2(int[] nums) {
        int res = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if(nums[i] > nums[j] * 2) {
                    res ++;
                }
            }
        }
        return res;
    }

    public static int reversePairs(int[] nums) {
        return process(nums, 0, nums.length - 1);
    }

    private static int process(int[] nums, int l, int r) {
        if(l == r) {
            return 0;
        }
        int m = l + ((r - l) >> 1);
        return process(nums, l, m) + process(nums, m + 1, r) + merge(nums, l, r, m);
    }

    private static int merge(int[] nums, int l, int r, int m) {
        int curAns = 0;
        int res = 0;
        int a = l;
        int b = m + 1;
        int index = 0;
        int[] help = new int[r - l + 1];

        while(a <= m) {
            while(b <= r && nums[a] > 2L * nums[b]) {
                curAns ++;
                b ++;
            }
            res += curAns;
            a ++;
        }

        a = l;
        b = m + 1;
        while(a <= m && b <= r) {
            if(nums[a] <= nums[b]) {
                help[index++] = nums[a++];
            }else {
                help[index++] = nums[b++];
            }
        }

        while(a <= m) {
            help[index++] = nums[a++];
        }
        while(b <= r) {
            help[index++] = nums[b++];
        }
        for (int i = 0; i < help.length; i++) {
            nums[l + i] = help[i];
        }
        return res;
    }
}
